import React, { createContext, useReducer } from "react";
import { produce } from "immer";
import type { ClassStateType, ClassReducerType, ContextType } from "./../../types/classificationType"



const initialState: ClassStateType = {
    prames: {
        categoryName: "",
        categoryId: undefined,
        parentCategoryId: undefined,
        sub: true
    },
    data: {
        count: 0,
        data: []
    },
    addOrEdit: false,
    type: "addFirst",
    dataItem: {
        categoryId: 0,
        parentCategoryId: 0,
        level: 1
    }
};


const reducer = produce((state: ClassStateType, action: ClassReducerType) => {
    switch (action.type) {
        case 'SET_PRAMES':
            state.prames = { ...action.payLoad, sub: state.prames.sub }
            break;
        case 'CLEAR_PRAMES':
            state.prames = initialState.prames
            break;
        case 'SET_RESDATA':
            state.data = action.payLoad
            break;
        case 'CHANGE_ADDOREDIT':
            state.addOrEdit = action.payLoad
            break;
        case 'CHANGE_TYPE':
            state.type = action.payLoad
            break;
        case 'SET_DATAITEM':
            state.dataItem = action.payLoad
            break;
        default: throw new Error('Unexpected action');
    }
});

export const ClassContext = createContext<ContextType>({} as ContextType);

const ClassificationProvider: React.FC<React.PropsWithChildren> = ({ children }) => {
    const [state, dispatch] = useReducer(reducer, initialState);
    return (<ClassContext.Provider value={{ state, dispatch }}>{children}</ClassContext.Provider>)
}

export default ClassificationProvider;